package admin;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import utils.Codification;
import utils.DomainDAORemote;
import utils.ResponseDAORemote;
import utils.ResticketDAORemote;
import utils.TechticketDAORemote;
import utils.UserDAORemote;
import utils.UserlogDAORemote;
import utils.UsertypeDAORemote;
import beans.AdminPageBean;
import dtos.DomainDTO;
import dtos.ResponseDTO;
import dtos.ResticketDTO;
import dtos.TechticketDTO;
import dtos.UserDTO;
import dtos.UserlogDTO;
import dtos.UsertypeDTO;

/**
 * 
 * @author Catalin Covaciu
 * 
 */
@ManagedBean(name = "ub")
@ViewScoped
public class CrudUserBean implements Serializable {
	private static final long serialVersionUID = -4557912074305667649L;

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());

	@EJB
	UserDAORemote udr;

	@EJB
	DomainDAORemote ddr;

	@EJB
	UsertypeDAORemote utdr;

	@EJB
	ResticketDAORemote rtdr;

	@EJB
	TechticketDAORemote ttdr;

	@EJB
	ResponseDAORemote rdr;

	@EJB
	UserlogDAORemote uldr;

	@ManagedProperty("#{adminPageBean}")
	AdminPageBean apb;

	public AdminPageBean getApb() {
		return apb;
	}

	public void setApb(AdminPageBean apb) {
		this.apb = apb;
	}

	private List<UserDTO> users;
	private List<DomainDTO> domains;
	private List<UsertypeDTO> ustypes;
	private UserDTO us;
	private String domain;
	private String ustype;
	private String active;
	private String[] isActive = { "Active", "Inactive" };
	private String search;
	private String email;
	private String username;
	private String name;
	private String password;
	private Properties prop;

	private String message;

	private String msgSuccessfullyAdded = bundle
			.getString("Beans_admin_crudUserBean_msgSuccessfullyAdded");
	private String msgSuccessfullyEdited = bundle
			.getString("Beans_admin_crudUserBean_msgSuccessfullyEdited");
	private String msgSuccessfullyDeleted = bundle
			.getString("Beans_admin_crudUserBean_msgSuccessfullyDeleted");
	private String msgSuccessfullyResetedPass = bundle
			.getString("Beans_admin_crudUserBean_msgSuccessfullyResetedPass");

	@PostConstruct
	public void init() {
		message = "";
		search = "";
		prop = new Properties();
		try {
			prop.load(getClass()
					.getResourceAsStream("/manager/user.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		us = new UserDTO();
		ustypes = utdr.getAllUsertypes();
		users = udr.getAllUsersDTO();
		domains = ddr.getAllDomains();
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
		createNewUsernameAndPassword();
	}

	/**
	 * Method used for generating username and email
	 */
	private void createNewUsernameAndPassword() {
		String nUsername = this.name.toLowerCase();
		String nUsername2 = this.name;
		String tempUsername = "";
		String tempUsername2 = "";

		String[] usernameArray = nUsername.split(" ");
		String[] usernameArray2 = nUsername2.split(" ");
		if (usernameArray.length != 1) {
			tempUsername = tempUsername + usernameArray[0] + "."
					+ usernameArray[1] + ".";
			tempUsername2 = tempUsername2 + usernameArray2[0] + "."
					+ usernameArray2[1] + ".";
			tempUsername = tempUsername.substring(0, tempUsername.length() - 1);
			tempUsername2 = tempUsername2.substring(0,
					tempUsername2.length() - 1);
		} else {
			tempUsername = usernameArray[0];
			tempUsername2 = usernameArray2[0];
		}
		setEmail(tempUsername2 + prop.getProperty("emailDomain"));
		setUsername(tempUsername);
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getActive() {
		return active;
	}

	public void setActive(String active) {
		this.active = active;
	}

	public String[] getIsActive() {
		return isActive;
	}

	public void setIsActive(String[] isActive) {
		this.isActive = isActive;
	}

	public String getUstype() {
		return ustype;
	}

	public void setUstype(String ustype) {
		this.ustype = ustype;
	}

	public List<UsertypeDTO> getUstypes() {
		return ustypes;
	}

	public void setUstypes(List<UsertypeDTO> ustypes) {
		this.ustypes = ustypes;
	}

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	public List<DomainDTO> getDomains() {
		return domains;
	}

	public void setDomains(List<DomainDTO> domains) {
		this.domains = domains;
	}

	public UserDTO getUs() {
		return us;
	}

	public void setUs(UserDTO us) {
		this.us = us;
	}

	public List<UserDTO> getUsers() {
		return users;
	}

	public void setUsers(List<UserDTO> users) {
		this.users = users;
	}

	public DomainDTO getDomain(int id) {
		return ddr.getDomain(id);
	}

	public UsertypeDTO getUserType(int id) {
		return utdr.getUsertype(id);
	}

	public UserDTO getUser(int id) {
		return udr.getUser(id);
	}

	public void goToCreate() {
		apb.setPage("createUser");
	}

	/**
	 * Function used for redirecting to users.xhtml
	 * 
	 * @return page for redirection
	 */
	public String goToUsers() {
		users = udr.getAllUsersDTO();
		search = "";
		return "users.xhtml";
	}

	/**
	 * Function used for redirecting to edit user
	 * 
	 * @return page for redirection
	 */
	public String goToEdit() {
		return "editUser.xhtml";
	}

	/**
	 * Method for adding a new user
	 * 
	 * @param event
	 */
	public void addUser(ActionEvent event) {
		DomainDTO d = ddr.getDomainByName(domain);
		UsertypeDTO ut = utdr.getUsertypeByName(ustype);
		us.setName(name);
		us.setEmail(email);
		us.setUsername(username);
		us.setIdUsertype(ut.getId());
		us.setIdDomain(d.getId());
		String[] tempStrings = us.getName().split(" ");
		String p1 = tempStrings[0].toLowerCase();
		String p2 = p1.concat(".");
		String p3 = p2.concat(tempStrings[1].toLowerCase());
		password = p3.concat(prop.getProperty("passwordEnding"));
		us.setPassword(new Codification().md5(password));
		us.setIsActive(1);
		udr.insertUser(us);
		users = udr.getAllUsersDTO();
		message = msgSuccessfullyAdded;
		apb.setPage("users");
	}

	/**
	 * Method for editing a user
	 * 
	 * @param event
	 */
	public void editUser(ActionEvent event) {
		DomainDTO d = ddr.getDomainByName(domain);
		UsertypeDTO ut = utdr.getUsertypeByName(ustype);
		us.setIdUsertype(ut.getId());
		us.setIdDomain(d.getId());
		if (active.equals("Active")) {
			us.setIsActive(1);
		} else {
			us.setIsActive(0);
		}
		UserDTO admin = udr.getAdmin();
		us.setIdUser(admin.getId());
		udr.insertUser(us);
		users = udr.getAllUsersDTO();
		message = msgSuccessfullyEdited;
		apb.setPage("users");
	}

	/**
	 * Action listener for deleting user
	 * 
	 * @param event
	 */
	// public void deleteUserListener(ActionEvent event) {
	// int a = Integer.parseInt(event.getComponent().getAttributes()
	// .get("userid").toString());
	// us = udr.getUser(a);
	// List<ResticketDTO> resTickets = rtdr.getResticketsByUser(us);
	// if (resTickets.size() > 0) {
	// for (ResticketDTO rest : resTickets) {
	// rtdr.deleteResticket(rest);
	//
	// }
	// }
	// List<TechticketDTO> techTickets = ttdr.getTechticketsByUser(us);
	// if (techTickets.size() > 0) {
	// for (TechticketDTO techt : techTickets) {
	// ttdr.deleteTechticker(techt);
	//
	// }
	// }
	// List<ResticketDTO> resTickets1 = rtdr.getAllRestickets();
	// List<TechticketDTO> techTickets1 = ttdr.getAllTechtickets();
	// List<ResponseDTO> answers = rdr.getAllResponsesByUserId(us.getId());
	// if (answers.size() > 0) {
	// for (ResponseDTO re : answers) {
	// for (ResticketDTO res : resTickets1) {
	// if (res.getIdResponse() == re.getId()) {
	// rtdr.deleteResticket(res);
	// }
	// }
	// rdr.deleteResponse(re);
	// for (TechticketDTO tes : techTickets1) {
	// if (tes.getIdResponse() == re.getId()) {
	// ttdr.deleteTechticker(tes);
	// }
	// }
	// rdr.deleteResponse(re);
	// }
	// }
	// List<UserlogDTO> logs = uldr.getAllUserlogsByUserId(us.getId());
	// if (logs.size() > 0) {
	// for (UserlogDTO log : logs) {
	// uldr.deleteUserlog(log);
	// }
	// }
	// udr.deleteUser(us);
	// users = udr.getAllUsersDTO();
	// message = msgSuccessfullyDeleted;
	// apb.setPage("users");
	// }

	public void deleteUserListener(ActionEvent event) {
		int a = Integer.parseInt(event.getComponent().getAttributes()
				.get("userid").toString());
		us = udr.getUser(a);
		if (checkDeleteUser(us)) {
			message = msgSuccessfullyDeleted;
			udr.deleteUser(us);
		} else {
			message = bundle.getString("Beans_admin_crudUserBean_msgUnsuccessfullyDeleted");
		}
		users = udr.getAllUsersDTO();
		apb.setPage("users");
	}

	private boolean checkDeleteUser(UserDTO modUser) {
		List<ResticketDTO> resTickets = rtdr.getResticketsByUser(modUser);
		List<TechticketDTO> techTickets = ttdr.getTechticketsByUser(modUser);
		List<ResponseDTO> answers = rdr
				.getAllResponsesByUserId(modUser.getId());
		List<UserlogDTO> logs = uldr.getAllUserlogsByUserId(modUser.getId());
		List<UserDTO> users = udr.getAllUsersDTO();
		boolean canDelete = true;
		if (!resTickets.isEmpty()) {
			canDelete = false;
		}
		if (!techTickets.isEmpty()) {
			canDelete = false;
		}
		if (!answers.isEmpty()) {
			canDelete = false;
		}
		if (!logs.isEmpty()) {
			canDelete = false;
		}
		for (UserDTO user : users) {
			if (user.getIdUser() == modUser.getId()) {
				canDelete = false;
			}
		}
		return canDelete;
	}

	/**
	 * Method to get the current user for editing
	 * 
	 * @param event
	 */
	public void getUserEdit(ActionEvent event) {
		int a = Integer.parseInt(event.getComponent().getAttributes()
				.get("userid").toString());
		us = udr.getUser(a);
		apb.setPage("editUser");
	}

	/**
	 * Methods for ordering users
	 * 
	 * @return the page for redirecting
	 */
	public void ascDomain() {
		users = udr.getUserOrderedByDomain();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descDomain() {
		users = udr.getUserOrderedByDomainDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void ascUsername() {
		users = udr.getUserOrderedByUsername();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descUsername() {
		users = udr.getUserOrderedByUsernameDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void ascUsertype() {
		users = udr.getUserOrderedByUsertype();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descUsertype() {
		users = udr.getUserOrderedByUsertypeDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void ascName() {
		users = udr.getUserOrderedByName();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descName() {
		users = udr.getUserOrderedByNameDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void ascEmail() {
		users = udr.getUserOrderedByEmail();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descEmail() {
		users = udr.getUserOrderedByEmailDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void ascIsactive() {
		users = udr.getUserOrderedByIsActive();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descIsactive() {
		users = udr.getUserOrderedByIsActiveDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void ascReplaced() {
		users = udr.getUserOrderedByReplacedby();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	public void descReplaced() {
		users = udr.getUserOrderedByReplacedbyDesc();
		orderUsers();
		message = "";
		apb.setPage("users");
	}

	/**
	 * Method for ordeing users
	 */
	public void orderUsers() {
		int i = 0;
		if (search.length() < 1)
			return;
		while (i < users.size()) {
			if (!users.get(i).getName().contains(search)) {
				users.remove(i);
			} else {
				i++;
			}
		}

	}

	public void searchUsers() {
		users = udr.getAllUsersDTO();
		orderUsers();
		System.out.println(users.size());
	}

	/**
	 * Method for reseting password
	 */
	public void resetPassword() {
		System.out.println(us.getName());
		String[] tempStrings = us.getName().split(" ");
		String p1 = tempStrings[0].toLowerCase();
		String p2 = p1.concat(".");
		String p3 = p2.concat(tempStrings[1].toLowerCase());
		password = p3.concat(prop.getProperty("passwordEnding"));
		us.setPassword(new Codification().md5(password));
		udr.insertUser(us);
		message = msgSuccessfullyResetedPass;
		apb.setPage("users");
	}

	public DomainDTO getDomainById(int id) {
		return ddr.getDomain(id);
	}

	public void goBack() {
		setMessage("");
		apb.setPage("users");
	}

	public String getMsgSuccessfullyAdded() {
		return msgSuccessfullyAdded;
	}

	public void setMsgSuccessfullyAdded(String msgSuccessfullyAdded) {
		this.msgSuccessfullyAdded = msgSuccessfullyAdded;
	}

	public String getMsgSuccessfullyEdited() {
		return msgSuccessfullyEdited;
	}

	public void setMsgSuccessfullyEdited(String msgSuccessfullyEdited) {
		this.msgSuccessfullyEdited = msgSuccessfullyEdited;
	}

	public String getMsgSuccessfullyDeleted() {
		return msgSuccessfullyDeleted;
	}

	public void setMsgSuccessfullyDeleted(String msgSuccessfullyDeleted) {
		this.msgSuccessfullyDeleted = msgSuccessfullyDeleted;
	}

	public String getMsgSuccessfullyResetedPass() {
		return msgSuccessfullyResetedPass;
	}

	public void setMsgSuccessfullyResetedPass(String msgSuccessfullyResetedPass) {
		this.msgSuccessfullyResetedPass = msgSuccessfullyResetedPass;
	}

}
